package com.hoshiicloud.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.GoodsBrand;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.goods.GoodsBrandMapper;
import com.hoshiicloud.goods.service.BrandCategoryService;
import com.hoshiicloud.goods.service.GoodsBrandService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品品牌表 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class GoodsBrandServiceImpl extends ServiceImpl<GoodsBrandMapper, GoodsBrand> implements GoodsBrandService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private BrandCategoryService brandCategoryService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private GoodsBrandMapper goodsBrandMapper;

    public static final String GOODS_ALL_BRAND = "goodsAllBrand";

    /**
     * @param id
     * @return GoodsBrand
     * @description: 根据id查询商品品牌表
     */
    @Override
    @Cacheable(cacheNames = "GoodsBrand", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品品牌表-查询商品品牌表 ")
    public GoodsBrand getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增商品品牌表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsBrand", allEntries = true)
    @Logable(authName = "商品管理-商品品牌表-新增商品品牌表")
    public boolean save(GoodsBrand entity) {

        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改商品品牌表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsBrand", allEntries = true)
    @Logable(authName = "商品管理-商品品牌表管理-修改商品品牌表")
    public boolean updateById(GoodsBrand entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper 查询条件
     * @return IPage
     * @description: 分页查询商品品牌表
     */
    @Override
    @Logable(authName = "商品管理-商品品牌表管理-分页查询商品品牌表")
    @Cacheable(cacheNames = "GoodsBrand", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public IPage getPage(IPage page, Wrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsBrand", allEntries = true)
    @Logable(authName = "商品管理-商品品牌表管理-删除商品品牌表")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        GoodsBrand entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除商品品牌表异常，无法找到商品品牌表记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsBrand", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品品牌表管理-根据id集合查询商品品牌表")
    public List<GoodsBrand> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }


    /**
     * 查询某个分类下的所有品牌信息
     */
    @Override
    public List<Map<String, Object>> getGoodsBrandsByCateId(Long cateId) {

        // 存放需要返回的数据
        List<Map<String, Object>> brandsMap = new ArrayList<>();

        // 查询某个类目下的所有品牌id
        /*List<BrandCategory> brandList = brandCategoryService.getBrandIdsByCategoryId(cateId);
        if (brandList.isEmpty()) {
            return brandsMap;
        }

        List<Long> idList = brandList.stream().map(s -> s.getBrandId()).collect(Collectors.toList());

        // 根据品牌id 集合查询品牌信息
        List<GoodsBrand> byIds = this.getByIds(idList, StringUtils.join(idList, ""));*/

        QueryWrapper<GoodsBrand> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(GoodsBrand::getDeleted, 0);
        List<GoodsBrand> byIds = baseMapper.selectList(wrapper);
        // 设置展示信息
        byIds.stream().forEach(s -> {
            Map<String, Object> map = new HashMap<>();
            map.put("label", s.getChineseName());
            map.put("value", s.getId());
            brandsMap.add(map);
        });

        // 根据品牌id, 查询所有的品牌信息
        return brandsMap;
    }

    @Override
    public List<Map<String, Object>> getAllGoodsBrand() {
        if (!redisTemplate.hasKey(GOODS_ALL_BRAND)) {
            QueryWrapper<GoodsBrand> goodsBrandQueryWrapper = new QueryWrapper<>();

            goodsBrandQueryWrapper.lambda()
                    .select(GoodsBrand::getId, GoodsBrand::getChineseName, GoodsBrand::getEnglishName);

            List<GoodsBrand> goodsBrandList = this.list(goodsBrandQueryWrapper);

            LinkedList<Map<String, Object>> returnGoodsBrandList = new LinkedList<>();

            for (GoodsBrand goodsBrand : goodsBrandList) {
                Map<String, Object> goodsBrandMap = new HashMap<>(16);
                goodsBrandMap.put("value", goodsBrand.getId());
                goodsBrandMap.put("label", goodsBrand.getChineseName());
                goodsBrandMap.put("englishLabel", goodsBrand.getEnglishName());
                returnGoodsBrandList.add(goodsBrandMap);
            }
            if (CollectionUtils.isEmpty(returnGoodsBrandList)) {
                throw new ServiceException("暂无品牌信息");
            }
            redisTemplate.opsForValue().set(GOODS_ALL_BRAND, returnGoodsBrandList, 23, TimeUnit.HOURS);
            return returnGoodsBrandList;
        } else {
            return (List<Map<String, Object>>) redisTemplate.opsForValue().get(GOODS_ALL_BRAND);
        }
    }
}
